﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace OmniKits.Core
{
    public class Retry
    {
        public static void DoRetry(Action action, int maxRetry, TimeSpan delay, TimeSpan? delayIncrement = null, TimeSpan? maxDelay = null)
        {
            if (delayIncrement == null)
                delayIncrement = delay;

            if (maxDelay == null)
                maxDelay = TimeSpan.MaxValue;

            int retry = 0;

            for (; ;)
            {
                try
                {
                    action();
                    return;
                }
                catch
                {
                    if (retry == maxRetry)
                        throw;
                }

                Thread.Sleep(delay);

                if (delay < maxDelay.Value)
                {
                    delay += delayIncrement.Value;
                    if (delay > maxDelay.Value)
                        delay = maxDelay.Value;
                }
            }
        }

        public static T DoRetry<T>(Func<T> func, int maxRetry, TimeSpan delay, TimeSpan? delayIncrement = null, TimeSpan? maxDelay = null)
        {
            if (delayIncrement == null)
                delayIncrement = delay;

            if (maxDelay == null)
                maxDelay = TimeSpan.MaxValue;

            int retry = 0;

            for (; ;)
            {
                try
                {
                    return func();
                }
                catch
                {
                    if (retry == maxRetry)
                        throw;
                }

                Thread.Sleep(delay);

                if (delay < maxDelay.Value)
                {
                    delay += delayIncrement.Value;
                    if (delay > maxDelay.Value)
                        delay = maxDelay.Value;
                }
            }
        }
    }
}
